package com.jiali.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiali.backend.Utils.UserServiceUtils;
import com.jiali.backend.common.ResponseResult;
import com.jiali.backend.controller.request.LoginRequest;
import com.jiali.backend.controller.request.RegisterRequest;
import com.jiali.backend.controller.request.UserInfoUpdateRequest;
import com.jiali.backend.mapper.UserMapper;
import com.jiali.backend.model.User;
import com.jiali.backend.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import static com.jiali.backend.constant.UserConstant.USER_LOGIN_STATE;


/**
 * @author piko
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-02-19 22:51:42
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserServiceUtils userServiceUtils;

    /**
     * 登录
     *
     * @author piko
     */
    @Override
    public ResponseResult<User> userLogin(LoginRequest loginRequest, HttpServletRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", loginRequest.getUserAccount());
        //查询用户是否存在
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return ResponseResult.fail(401, "账号不存在", null);
        }
        String encryptedPassword = userServiceUtils.encryptionPassword(loginRequest.getUserPassword());
        if (encryptedPassword.equals(user.getPassword())) {
            User safeUser = userServiceUtils.safeUser(user);
            request.getSession().setAttribute(USER_LOGIN_STATE, safeUser);
            return ResponseResult.success(200, "OK", safeUser);
        }

        return ResponseResult.fail(401, "账号或密码错误", null);
    }

    /**
     * 注册
     *
     * @author piko
     */
    @Override
    public ResponseResult<User> userRegister(RegisterRequest registerUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", registerUser.getUserAccount());
        Long l = userMapper.selectCount(queryWrapper);
        if (l > 0) {
            return null;
        }
        User user = new User();
        user.setUserAccount(registerUser.getUserAccount());
        user.setPassword(userServiceUtils.encryptionPassword(registerUser.getUserPassword()));
        userMapper.insert(user);
        //脱敏
        user = userServiceUtils.safeUser(user);
        return ResponseResult.success(user);
    }

    /**
     * 退出登录
     *
     * @author piko
     */
    @Override
    public ResponseResult<User> userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        return ResponseResult.success(200, "OK", user);
    }

    /**
     * 获取当前登录用户
     */
    @Override
    public ResponseResult<User> getCurrentUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        return ResponseResult.success(user);
    }

    /**
     * 更新用户信息
     */
    @Override
    public ResponseResult<User> updateUserInfo(UserInfoUpdateRequest userInfoUpdateRequest, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);

        if (currentUser == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 构建更新对象
        User updateUser = new User();
        updateUser.setId(currentUser.getId());
        if (userInfoUpdateRequest.getUsername() != null) {
            updateUser.setUsername(userInfoUpdateRequest.getUsername());
        }
        if (userInfoUpdateRequest.getAvatarUrl() != null) {
            updateUser.setAvatarUrl(userInfoUpdateRequest.getAvatarUrl());
        }
        if (userInfoUpdateRequest.getPhone() != null) {
            updateUser.setPhone(userInfoUpdateRequest.getPhone());
        }

        // 执行更新
        int updated = userMapper.updateById(updateUser);
        if (updated > 0) {
            // 更新session中的用户信息
            User newUser = userMapper.selectById(currentUser.getId());
            request.getSession().setAttribute(USER_LOGIN_STATE, userServiceUtils.safeUser(newUser));
            return ResponseResult.success(200,"OK",userServiceUtils.safeUser(newUser));
        }
        return ResponseResult.fail(500, "更新失败", null);
    }
    @Override
    public ResponseResult<User> updateAvatar(MultipartFile file, HttpServletRequest request) {
        // 获取当前用户
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (currentUser == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 构建更新对象
        User updateUser = new User();
        updateUser.setId(currentUser.getId());
        updateUser.setAvatarUrl(currentUser.getAvatarUrl()); // 实际路径由controller处理

        // 执行更新
        int updated = userMapper.updateById(updateUser);
        if (updated > 0) {
            User newUser = userMapper.selectById(currentUser.getId());
            request.getSession().setAttribute(USER_LOGIN_STATE, userServiceUtils.safeUser(newUser));
            return ResponseResult.success(userServiceUtils.safeUser(newUser));
        }
        return ResponseResult.fail(500, "头像更新失败", null);
    }
}




